import Vue from 'vue'
import config from '@/config/index.js'
import axios from 'axios'
import qs from 'qs'
import store from "@/store/index.js";
import {
    refreshToken,
    clearAllUserInfo
} from './api'
axios.defaults.baseURL = config.baseURL
axios.defaults.timeout = 100000
let loadingNum = 0;
let loadingInstance;
let flag = true;
// 封装警告消息
var showMsg = function ({
    type = 'warning',
    showClose = false,
    msg = '请求失败',
    duration = 1000
}) {
    return Vue.prototype.$message({
        type: type,
        showClose: showClose,
        message: msg,
        duration: duration
    })
}
Vue.prototype.$showMsg = showMsg

axios.interceptors.request.use(config => {
    // 如果请求的方法是get，要处理数组
    if (config.method === 'get') {
        //如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
        config.paramsSerializer = function (params) {
            return qs.stringify(params, {
                arrayFormat: 'repeat'
            })
        }
    }
    // 加载图标
    if (loadingNum == 0) {
        loadingInstance = Vue.prototype.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(230, 230, 230, .5)', //遮罩层颜色
            fullscreen: true
        })
    }
    loadingNum++;

    // 登录授权 请求验证是否有token  需要授权的 API ，必须在请求头中使用 `Authorization` 字段提供 `token` 令牌
    console.log(localStorage.token_type + ' ' + localStorage.access_token)
    if (localStorage.access_token != undefined)
        config.headers.Authorization = (localStorage.token_type + ' ' + localStorage.access_token) || '';
    return config // 必须返回否则没有值
}, error => {
    // 关闭加载弹窗
    loadingNum--
    if (loadingNum == 0) {
        loadingInstance.close()
    }
    Promise.reject(error)
})

axios.interceptors.response.use(async response => {

    // 关闭加载弹窗
    loadingNum--
    if (loadingNum == 0) {
        loadingInstance.close()
    }
    const {
        status,
        statusText,
        data,
    } = response

    if (status !== 200) {
        throw new Error(statusText)
    }

    let {
        code
    } = data;

    if (code == 1013) {
        showMsg({
            msg: '注册失败'
        })
        return Promise.reject('error');
    } else if (code == 1014) {
        showMsg({
            type: 'success',
            msg: '注册成功'
        })
        // return Promise.reject('error');
    } else if (code == 1402) {
        showMsg({
            msg: '注册超时'
        })
        return Promise.reject('error');
    } else if (code == 1005) {
        showMsg({
            msg: '无权限访问'
        })
        return Promise.reject('error');
    } else if (code == 1001) {
        showMsg({
            msg: '客户端认证失败,请重新登录！'
        })
        return Promise.reject('error');
    } else if (code == 1002) {
        showMsg({
            msg: '用户名或密码错误'
        })
        return Promise.reject('error');
    } else if (code == 504) {
        showMsg({
            msg: '系统错误'
        })
        return Promise.reject('error');
    } else if (code == 1004 && flag == true) {
        // 只请求一次
        flag = false;
        // 刷新token值
        store.commit('m_user/SET_accessToken', '-1');
        console.log('刷新token值')
        let code = await refreshToken();
        if (code == 200) {
            // 刷新成功

        } else {
            // 刷新失败
            showMsg({
                msg: '登录失效，请前去登录！'
            })
        }
        flag = true;
    }
    return data
}, error => {
    const {
        response: {
            data
        }
    } = error
    let {
        code,
        msg
    } = data;
    console.log(data, '500')
    // 用户名或密码错误
    if (code == '1002') {
        showMsg({
            msg
        })
    } else {
        showMsg({
            msg: '服务器出错了'
        })
    }

    // 关闭加载弹窗
    loadingNum--
    if (loadingNum === 0) {
        loadingInstance.close()
    }
    return Promise.reject(error)
})

Vue.prototype.$http = axios

export default axios